import QtQuick 2.15
import QtQuick.Controls 2.15
import QtMultimedia
import QtQml
import QtQuick.Controls.Material 2.0
import Qt.labs.qmlmodels 1.0
import QtQuick.Dialogs
import "Utils.js" as Utils
import BNSPlayer

Rectangle {
    color: "#00ffffff"
    anchors.fill: parent
    id: rootItem

    implicitWidth: 1280
    implicitHeight: 720

    signal openVideoFileCommand(var fileUrl)

    signal progressSliderMoved(var value)

    property bool fullScreenState: false

    property FrameRenderer videoRenderer: frameRenderer

    property url fileURL

    property real decodingPosition: 0

    property real decodingDuration: 0

    property string decoderState: "Stopped"

    property real audioVolume: 1

    property real playSpeed: 1

    FileDialog {
        id: fileDialog
        currentFolder: rootItem.fileURL
        selectedNameFilter.index: 1
        title: qsTr("请选择一个视频文件...")
        nameFilters: ["Media Files (*.mp4 *.avi *.mkv *.mp3 *.wav)", "All Files (*.*)"]

        onAccepted: rootItem.openVideoFileCommand(selectedFile)
    }

    Timer {
        id: hideCtrlTimer
        interval: 1500
        repeat: true
        running: true

        property bool blockTimer: false

        onTriggered: {
            if (blockTimer)
                return

            if (rootItem.decoderState === "Stopped")
                return

            topPanel.hide()
            bottomPanel.hide()
            globalMouseArea.cursorShape = "BlankCursor"
        }
    }

    FrameRenderer {
        id: frameRenderer
        x: 0
        y: 0
        width: parent.width
        height: parent.height
    }

    MouseArea {
        id: globalMouseArea
        hoverEnabled: true
        anchors.fill: parent
        z: 10
        propagateComposedEvents: true
        onPressed: (event)=> event.accepted = false
        onReleased: (event)=> event.accepted = false
        onClicked: (event)=> event.accepted = false
        onEntered: {

        }
        onExited: {

        }

        onPositionChanged: {
            hideCtrlTimer.interval = 1500
            hideCtrlTimer.restart()
            topPanel.show()
            bottomPanel.show()
            cursorShape = Qt.ArrowCursor
        }

        ControlPanel {
            height: 35
            width: parent.width
            id: topPanel
            y: slidingState ? 0 : 0 - height // 根据 visible 改变位置

            Text {
                x: 10
                id: filenameLabel
                color: "#efefef"
                text: Utils.baseNameFromURL(rootItem.fileURL)
                font.pixelSize: 20
                font.styleName: "Regular"
                font.bold: true
                font.family: "AaPGZYSWZ (Non-Commercial Use)"
                anchors.verticalCenter: parent.verticalCenter
            }

            BnsButton {
                anchors.right: parent.right
                anchors.rightMargin: 10
                width: 30
                height: 30
                anchors.verticalCenter: parent.verticalCenter
                normalIcon: "../images/list.png"
                hoveredIcon: normalIcon
                pressedIcon: normalIcon

                onClicked: {
                    playlistPanel.open()
                }

                Popup {
                    width: rootItem.width * 2 / 5
                    height: rootItem.height
                    x: rootItem.width - width
                    y: 0
                    id: playlistPanel
                    parent: rootItem
                    padding: 0
                    margins: 0

                    background: Rectangle {
                        color: "#00ffffff"
                    }

                    MouseArea {
                        anchors.fill: parent
                        hoverEnabled: true
                        propagateComposedEvents: true
                        onPressed: (mouse) => mouse.accepted = false
                        onReleased: (mouse) => mouse.accepted = false
                        onClicked: (mouse) => mouse.accepted = false
                        onEntered: hideCtrlTimer.blockTimer = true
                        onExited: hideCtrlTimer.blockTimer = false

                        PlaylistView {
                            anchors.fill: parent
                            currentFile: rootItem.fileURL

                            onCurrentFileChanged: {
                                if(currentFile !== rootItem.fileURL) {
                                    rootItem.openVideoFileCommand(currentFile);
                                }
                            }
                        }
                    }
                }
            }
        }

        ControlPanel {
            height: 85
            width: parent.width
            id: bottomPanel
            y: slidingState ? parent.height - height : parent.height // 根据 visible 改变位置

            Slider {
                height: 25
                width: parent.width
                id: progressBar
                from: 0
                to: rootItem.decodingDuration
                value: rootItem.decodingPosition

                MouseArea {
                    z: 9
                    hoverEnabled: true
                    anchors.fill: parent
                    propagateComposedEvents: true
                    onPressed: (event) => event.accepted = false
                    onReleased: (event) => event.accepted = false
                    onClicked: (event) => event.accepted = false
                    onEntered: hideCtrlTimer.blockTimer = true
                    onExited: hideCtrlTimer.blockTimer = false
                }

                property real lastValue: -100
                Timer {
                    id: sliderSignalBlockTimer
                    interval: 500
                    repeat: false
                    onTriggered: parent.lastValue = -100
                }

                onMoved: {
                    if (lastValue === value)
                        return

                    console.log(value)
                    rootItem.progressSliderMoved(value)
                    sliderSignalBlockTimer.restart()
                    lastValue = value
                }

                background: Rectangle {
                    x: parent.leftPadding
                    y: parent.topPadding + parent.availableHeight / 2 - height / 2
                    implicitWidth: 200
                    implicitHeight: 7
                    width: parent.availableWidth
                    height: 7
                    radius: 2
                    color: "#bdbdbd"
                }

                Rectangle {
                    width: parent.visualPosition * (parent.width - parent.leftPadding
                                                    - parent.rightPadding)
                    height: 10
                    color: "#efefef"
                    radius: 2
                    x: parent.leftPadding
                    y: parent.topPadding + parent.availableHeight / 2 - height / 2
                }

                handle: Rectangle {
                    color: "#efefef"
                    x: parent.leftPadding + parent.visualPosition
                        * (parent.availableWidth - width)
                    y: parent.topPadding + parent.availableHeight / 2 - height / 2
                    implicitWidth: 20
                    implicitHeight: 20
                    radius: 12
                    border.color: "#9f9f9f"
                    border.width: 2
                }
            }

            Rectangle {
                width: parent.width
                height: parent.height - progressBar.height
                y: 25
                x: 0
                color: "#333333"

                Text {
                    id: timeLabel
                    text: Utils.timeToString(
                                rootItem.decodingPosition) + " / " + Utils.timeToString(
                                rootItem.decodingDuration)
                    font.pixelSize: 14
                    x: 10
                    color: "#efefef"
                }

                Rectangle {
                    width: 200
                    height: 40
                    anchors.centerIn: parent
                    color: "#333333"

                    MouseArea {
                        z: 9
                        hoverEnabled: true
                        anchors.fill: parent
                        propagateComposedEvents: true
                        onPressed: (mouse) => mouse.accepted = false
                        onReleased: (mouse) => mouse.accepted = false
                        onClicked: (mouse) => mouse.accepted = false
                        onEntered: hideCtrlTimer.blockTimer = true
                        onExited: hideCtrlTimer.blockTimer = false

                        BnsButton {
                            id: previousBtn
                            normalIcon: "qrc:/images/previous.svg"
                            hoveredIcon: "qrc:/images/previousHover.svg"
                            pressedIcon: "qrc:/images/previousPress.svg"
                            width: 40
                            height: 40
                            imageWidth: 25
                            imageHeight: 25
                            x: 0
                            y: 0
                            ToolTip.visible: down
                            ToolTip.text: qsTr("上一个")
                        }

                        BnsButton {
                            id: backwordBtn
                            normalIcon: "qrc:/images/backword.svg"
                            hoveredIcon: "qrc:/images/backword.svg"
                            pressedIcon: "qrc:/images/backword.svg"
                            width: 40
                            height: 40
                            imageWidth: 25
                            imageHeight: 25
                            x: 40
                        }

                        BnsButton {
                            id: playBtn
                            width: 40
                            height: 40
                            x: 80

                            state: rootItem.decoderState === "Playing" ? "Playing" : "Pausing"

                            states: [
                                State {
                                    name: "Playing"
                                    PropertyChanges {
                                        target: playBtn
                                        normalIcon: "../images/pause.svg"
                                        hoveredIcon: "../images/pauseHover.svg"
                                        pressedIcon: "../images/pausePress.svg"
                                    }
                                },
                                State {
                                    name: "Pausing"
                                    PropertyChanges {
                                        target: playBtn
                                        normalIcon: "../images/play.svg"
                                        hoveredIcon: "../images/playHover.svg"
                                        pressedIcon: "../images/playPress.svg"
                                    }
                                }
                            ]

                            onClicked: {
                                rootItem.decoderState = state === "Playing" ? "Pausing" : "Playing"
                            }
                        }

                        BnsButton {
                            id: forwardBtn
                            normalIcon: "qrc:/images/forward.svg"
                            hoveredIcon: "qrc:/images/forward.svg"
                            pressedIcon: "qrc:/images/forward.svg"
                            width: 40
                            height: 40
                            imageWidth: 25
                            imageHeight: 25
                            x: 120
                        }

                        BnsButton {
                            id: nextBtn
                            normalIcon: "../images/next.svg"
                            hoveredIcon: "../images/nextHover.svg"
                            pressedIcon: "../images/nextPress.svg"
                            width: 40
                            height: 40
                            imageWidth: 25
                            imageHeight: 25
                            x: 160
                            y: 0
                        }
                    }
                }

                Rectangle {

                    height: 30
                    width: 120
                    x: parent.width - 10 - width
                    anchors.verticalCenter: parent.verticalCenter
                    color: parent.color

                    MouseArea {
                        z: 9
                        hoverEnabled: true
                        anchors.fill: parent
                        propagateComposedEvents: true
                        onPressed: mouse.accepted = false
                        onReleased: mouse.accepted = false
                        onClicked: mouse.accepted = false
                        onEntered: hideCtrlTimer.blockTimer = true
                        onExited: hideCtrlTimer.blockTimer = false

                        BnsButton {
                            height: 30
                            width: 30
                            id: volumeBtn
                            normalIcon: "qrc:/images/volumeHigh.png"
                            hoveredIcon: "qrc:/images/volumeHigh.png"
                            pressedIcon: "qrc:/images/volumeHigh.png"
                            imageWidth: 20
                            imageHeight: 20
                            onClicked: {
                                var globalPos = mapToItem(rootItem, 0, 0)
                                volumeBarView.x = globalPos.x
                                volumeBarView.y = globalPos.y - volumeBarView.height - 5
                                volumeBarView.open()
                            }

                            Popup {
                                id: volumeBarView
                                padding: 0
                                margins: 0
                                height: 160
                                width: 30
                                parent: rootItem
                                onOpened: hideCtrlTimer.blockTimer = true
                                onClosed: hideCtrlTimer.blockTimer = false
                                contentItem: VolumeBarView {
                                    sliderValue: audioVolume

                                    onSliderValueChanged: {
                                        if (sliderValue !== audioVolume)
                                            audioVolume = sliderValue

                                        if (audioVolume > (2 / 3)) {
                                            volumeBtn.normalIcon = volumeBtn.hoveredIcon
                                                    = volumeBtn.pressedIcon
                                                    = "qrc:/images/volumeHigh.png"
                                        } else if (audioVolume > (1 / 3)) {
                                            volumeBtn.normalIcon = volumeBtn.hoveredIcon
                                                    = volumeBtn.pressedIcon
                                                    = "qrc:/images/volumeMiddle.png"
                                        } else if (audioVolume === 0) {
                                            volumeBtn.normalIcon = volumeBtn.hoveredIcon
                                                    = volumeBtn.pressedIcon
                                                    = "qrc:/images/volumeCross.png"
                                        } else {
                                            volumeBtn.normalIcon = volumeBtn.hoveredIcon
                                                    = volumeBtn.pressedIcon
                                                    = "qrc:/images/volumeLow.png"
                                        }
                                    }
                                }

                                background: Rectangle {
                                    color: "#333333"
                                    radius: 4
                                }
                            }
                        }

                        BnsButton {
                            width: 40
                            height: 30
                            x: 80
                            imageWidth: 20
                            imageHeight: 20
                            id: fullScreenSwitchBtn

                            state: rootItem.fullScreenState ? "fullScreenExit" : "fullScreenEnter"

                            states: [
                                State {
                                    name: "fullScreenEnter"
                                    PropertyChanges {
                                        target: fullScreenSwitchBtn
                                        normalIcon: "qrc:/images/fullScreenEnter.svg"
                                        hoveredIcon: "qrc:/images/fullScreenEnter.svg"
                                        pressedIcon: "qrc:/images/fullScreenEnter.svg"
                                    }
                                },
                                State {
                                    name: "fullScreenExit"
                                    PropertyChanges {
                                        target: fullScreenSwitchBtn
                                        normalIcon: "qrc:/images/fullScreenExit.svg"
                                        hoveredIcon: "qrc:/images/fullScreenExit.svg"
                                        pressedIcon: "qrc:/images/fullScreenExit.svg"
                                    }
                                }
                            ]

                            onClicked: {
                                rootItem.fullScreenState = !rootItem.fullScreenState
                            }
                        }

                        Button {
                            id: speedBtn
                            text: "1x"
                            display: AbstractButton.IconOnly
                            width: 40
                            height: 30
                            anchors.verticalCenter: parent.verticalCenter
                            x: 30
                            background: Rectangle {
                                color: parent.pressed ? "#232323" : parent.hovered ? "#434343" : "#333333"
                                anchors.fill: parent
                                radius: 8
                            }
                            Text {
                                text: parent.text
                                anchors.fill: parent
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                                color: "#efefef"
                                font.pixelSize: 16
                            }

                            onClicked: {
                                var globalPos = mapToItem(rootItem, 0, 0)
                                speedListView.x = globalPos.x
                                speedListView.y = globalPos.y - speedListView.height - 5
                                speedListView.open()
                            }

                            Popup {

                                width: 61
                                height: 201
                                parent: rootItem
                                padding: 0
                                margins: 0

                                Timer {
                                    id: speedListClostTimer
                                    interval: 100
                                    onTriggered: {
                                        speedListView.close()
                                    }
                                }

                                onOpened: {
                                    hideCtrlTimer.blockTimer = true
                                }
                                onClosed: {
                                    hideCtrlTimer.blockTimer = false
                                }

                                id: speedListView
                                contentItem: SpeedListView {
                                    anchors.fill: parent
                                    selectedIndex: 1
                                    onSelectedIndexChanged: {
                                        speedListClostTimer.restart()
                                        var labels = ["0.5x", "1x", "1.5x", "2x", "4x"]
                                        var speedStr = speedBtn.text = labels[selectedIndex]
                                        playSpeed = Number(
                                                    speedStr.substring(
                                                        0,
                                                        speedStr.lastIndexOf(
                                                            'x')))
                                    }
                                }

                                background: Rectangle {
                                    color: "#333333"
                                    radius: 4
                                }
                            }
                        }
                    }
                }
            }
        }

        Rectangle {
            id: centerPanel
            width: parent.width
            height: parent.height - bottomPanel.height - topPanel.height
            anchors.top: topPanel.bottom
            color: "#00ffffff"
            visible: rootItem.decoderState === "Stopped" ? true : false

            onVisibleChanged: {
                if(visible === true)
                    console.log(rootItem.decoderState)
            }

            Button {
                text: "打开文件"
                display: AbstractButton.IconOnly
                anchors.centerIn: parent
                width: 89
                height: 40
                background: Rectangle {
                    color: parent.pressed ? "#232323" : parent.hovered ? "#434343" : "#333333"
                    anchors.fill: parent
                    radius: 8
                }
                Text {
                    text: parent.text
                    anchors.fill: parent
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    color: "#efefef"
                    font.pixelSize: 16
                }

                onClicked: fileDialog.open()
            }
        }
    }
}
